# -*- coding: utf-8 -*-
import datetime
import json
from odoo import http
import time
from odoo.addons.weixin.api.session_manager import session_obj
import logging

_logger = logging.getLogger(__name__)


class WliotDeviceController(http.Controller):

    @http.route('/wliot/device/queryDevices', auth='none')
    def queryDevices(self, **kw):
        ''' 按条件查询设备 '''
        try:
            _logger.info("---获取设备--")
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            partner_name = kw.get('partnerName')
            if not partner_name:
                partner_name = partner.name
            ptn = http.request.env['res.partner'].sudo().search([
                ('name', '=', partner_name)
            ])
            medium = kw.get('medium')
            valve_type = kw.get('valveType')
            device_status = kw.get('deviceStatus')
            running_status = kw.get('runningStatus')

            if medium == u'全部':
                ppm_type_doamin = []
            else:
                ppm_type_doamin = [('name', '=', medium)]
            ppm_type = http.request.env['wliot.ppm.type'].sudo().search(ppm_type_doamin)

            if valve_type == u'全部':
                valve_type_domain = [('ppm_type_id', 'in', ppm_type.ids)]
            else:
                valve_type_domain = [('ppm_type_id', 'in', ppm_type.ids), ('valve_type', '=', valve_type)]
            products = http.request.env['wliot.product'].sudo().search(valve_type_domain)

            if device_status == 'all':
                if running_status == 'all':
                    device_domain = [('product_id', 'in', products.ids), ('partner_id', 'in', ptn.get_child())]
                else:
                    device_domain = [('product_id', 'in', products.ids), ('running_status', '=', running_status),
                                     ('partner_id', 'in', ptn.get_child())]
            else:
                if running_status == 'all':
                    device_domain = [('product_id', 'in', products.ids), ('status', '=', device_status),
                                     ('partner_id', 'in', ptn.get_child())]
                else:
                    device_domain = [('product_id', 'in', products.ids), ('status', '=', device_status),
                                     ('running_status', '=', running_status), ('partner_id', 'in', ptn.get_child())]
            devices = http.request.env['wliot.device'].sudo().search(device_domain)

            data = []
            for device in devices:
                data.append(
                    {
                        'barcode': device.barcode,
                        'valveType': device.get_product().valve_type,
                        'location': device.location,
                        'runningStatus': device.running_status,
                        'lostin': device.lostin,
                        'outrange': device.outrange,
                        'alarm': device.alarm,
                        'attributes': device.get_attributes()
                    }
                )
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data,
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error,
                })

    @http.route('/wliot/device/searchDevices', auth='public')
    def searchDevices(self, **kw):
        ''' 搜索设备 '''
        try:
            barcode = kw.get('barcode')
            partner_name = kw.get('partnerName')
            ptn = http.request.env['res.partner'].sudo().search([
                ('name', '=', partner_name)
            ])
            devices = http.request.env['wliot.device'].sudo().search([
                ('barcode', 'ilike', barcode),
                ('partner_id', '=', ptn.id)
            ])
            data = []
            for device in devices:
                data.append(
                    {
                        'barcode': device.barcode,
                        'valveType': device.get_product().valve_type,
                        'location': device.location,
                        'runningStatus': device.running_status,
                        'lostin': device.lostin,
                        'outrange': device.outrange,
                        'alarm': device.alarm,
                        'attributes': device.get_attributes()
                    }
                )
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data,
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'message': error,
                    'code': 500
                })

    @http.route('/wliot/device/queryValveTypes', auth='public')
    def queryValveTypes(self, **kw):
        ''' 查询阀门类型 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            products = http.request.env['wliot.product'].sudo().search([])
            data = []
            for product in products:
                data.append(product.valve_type)
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data,
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error,
                })

    @http.route('/wliot/device/queryPpmTypes', auth='public')
    def queryPpmTypes(self, **kw):
        ''' 查询传感器类型 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            ppm_types = http.request.env['wliot.ppm.type'].sudo().search([])
            data = []
            for ppm_type in ppm_types:
                data.append(ppm_type.name)
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data,
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/device/querySensors', auth='public')
    def querySensors(self, **kw):
        ''' 查询传感器清单 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': ''
                })
            sensors = http.request.env['wliot.ppm.sensor'].sudo().search([

            ])
            devices = http.request.env['wliot.device'].sudo().search([
                ('partner_id', 'in', partner.get_child()),
            ])
            in_using_sensor_ids = []
            for device in devices:
                in_using_sensor_ids.append(device.ppm_sensor_id.id)
            data = []
            for sensor in sensors:
                if sensor.id not in in_using_sensor_ids:
                    data.append({
                        'sensorNo': sensor.barcode,
                        'sensorName': sensor.barcode,
                        'calibration': http.request.env['ir.config_parameter'].get_param('default_calibration')
                    })
            return json.dumps({
                'message': u'查询成功！',
                'success': True,
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/device/addMaintainRecord', auth='public', csrf=False)
    def addMaintainRecord(self, **kw):
        ''' 添加维护记录 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': ''
                })
            barcode = kw.get('barcode')
            description = kw.get('description')
            uploadtime = kw.get('time')
            http.request.env['wliot.device.maintain.record'].sudo().create({
                'device': http.request.env['wliot.device'].sudo().search([('barcode', '=', barcode)]).id,
                'partner_id': http.request.env['res.partner'].sudo().search([('name', '=', partner.name)]).id,
                'description': description,
                'time': self.get_beijing_datetime(uploadtime)
            })
            return json.dumps({
                'code': 200,
                'success': True,
                'message': u'添加成功'
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/device/queryDeviceDetail', auth='public')
    def queryDeviceDetail(self, **kw):
        ''' 查询设备详情 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': ''
                })
            type = kw.get('type')
            barcode = kw.get('barcode')
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            data = {}
            if type == 'basic':
                data = {
                    'medium': device.get_ppm_type(),
                    'valveType': device.get_product().valve_type,
                    'barcode': barcode,
                    'name': device.get_product().name,
                    'manufactureDate': device.manufacture_date,
                    'installDate': device.install_date,
                    'location': device.location,
                    'material': device.get_product().material,
                    'materialFile': '',
                    'ultimateUseTemp': device.get_product().ultimate_use_temp,
                    'ultimateUseHumi': device.get_product().ultimate_use_humi,
                    'limitDetectionRange': device.get_product().limit_detection_range,
                    'cardNo': device.card_no,
                    'IMEI': device.IMEI,
                    'attributes': device.get_attributes(),
                }
            if type == 'check':
                indicator_value = device.get_indicator_value()
                if indicator_value:
                    update_time = datetime.datetime.strptime(indicator_value.update_time, "%Y-%m-%d %H:%M:%S")
                    data = {
                        'temperature': indicator_value.temp_present_value,
                        'ppmMin': indicator_value.gas_present_value,
                        'ppmDay': indicator_value.gas_day_avg_value,
                        'alarm': indicator_value.gas_alarm_value,
                        'runningStatus': indicator_value.running_status,
                        'updateTime': update_time.strftime("%Y-%m-%d %H:%M:%S")
                    }
                else:
                    return json.dumps({
                        'code': 400,
                        'success': False,
                        'message': u'该设备没有投入使用，暂时没有检测信息'
                    })
            if type == 'set':
                log = device.env['wliot.device.command.log'].sudo().search([
                    ('device', '=', device.id),
                    ('order_type', '=', 'setting')
                ], order='code_time desc', limit=1)
                code_status = ''
                if not log:
                    code_status = 'none'
                else:
                    if log.status == 'send':
                        code_status = 'excuting'
                    elif log.status == 'work':
                        code_status = 'success'
                    elif log.status == 'fail':
                        code_status = 'fail'
                data = {
                    'alarm': device.get_indicator_value().gas_alarm_value,
                    'frequence': device.get_indicator_value().frequence,
                    'sensorNo': device.get_ppm_sensor().barcode,
                    'sensorName': device.get_ppm_sensor().barcode,
                    'calibration': device.get_product().ppm_calibration,
                    'settingLog': device.get_command_logs(),
                    'code_status': code_status,
                    'setting_permission': partner.setting_permission
                }
            if type == 'control':
                log = device.env['wliot.device.command.log'].sudo().search([
                    ('device', '=', device.id),
                    ('order_type', '=', 'control')
                ], order='code_time desc', limit=1)
                code_status = ''
                if not log:
                    code_status = 'none'
                else:
                    if log.status == 'send':
                        code_status = 'excuting'
                    elif log.status == 'work':
                        code_status = 'success'
                    elif log.status == 'fail':
                        code_status = 'fail'
                data = {
                    'controlType': device.mode,
                    'opendegree': device.get_opendegree(),
                    'codeBack': True,
                    'controlLog': device.get_control_logs(),
                    'code_status': code_status,
                    'control_permission': partner.control_permission
                    # 'none', 'excuting','success', 'fail'
                }
            if type == 'other':
                data = {
                    'changeSensorTime': device.get_ppm_sensor().deadline_date,
                    'instruction': u'就是这么用的',
                    'maintainLog': device.get_maintain_logs(),
                }
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data,
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/device/verifyPassword', auth='none')
    def verifyPassword(self, **kw):
        try:
            password = kw.get('password')
            password = str(password)
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': u'用户不存在'
                })
            if not partner.control_permission:
                return json.dumps({
                    'success': False,
                    'code': 400,
                    'message': u'该用户没有控制权限'
                })
            if partner.password == password:
                partner.write({
                    'wrong_count': 0
                })
                return json.dumps({
                    'success': True,
                    'code': 200,
                    'message': u'验证成功！'
                })
            else:
                if partner.wrong_count < 4:
                    partner.write({
                        'wrong_count': partner.wrong_count + 1
                    })
                    return json.dumps({
                        'success': False,
                        'code': 400,
                        'message': u'密码验证错误，您还有%s次机会就将锁定，请检查后再输入' % (5 - partner.wrong_count)
                    })
                else:
                    partner.write({
                        'wrong_count': 0,
                        'control_permission': False
                    })
                    return json.dumps({
                        'success': False,
                        'code': 400,
                        'message': u'已有5次密码验证错误，控制权限已锁定，请联系管理员解锁'
                    })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 400,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/device/queryHistoryData', auth='public')
    def queryHistoryData(self, **kw):
        ''' 查询设备历史/泄露数据 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': u'用户不存在'
                })

            pageSize = kw.get("pageSize", 7)
            pageSize = int(pageSize)
            pageNum = kw.get("pageNum", 1)
            pageNum = int(pageNum)
            offser_val = (pageNum - 1) * pageSize
            _logger.info('*****************1')
            type = kw.get('type')
            type = str(type)
            barcode = kw.get('barcode')
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            start_time = kw.get('startTime')
            start_time = self.timestamp2datetime(start_time)
            _logger.info(start_time)
            end_time = kw.get('endTime')
            end_time = self.timestamp2datetime(end_time)
            _logger.info(end_time)
            hours = (end_time - start_time).seconds / 3600
            _logger.info(hours)
            days = (end_time - start_time).days
            _logger.info(days)
            _logger.info('*****************2')
            data = {}
            if type == 'history':
                if hours <= 1:
                    sql = "select to_char(collection_date,'HH24:MI') as index_time, " \
                          "normal_gas_value as value " \
                          "from wliot_device_indicator_log a " \
                          "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.abnormal_gas_value=0 " \
                          "order by to_char(collection_date,'HH24:MI') asc " % (start_time, end_time)
                    http.request.env.cr.execute(sql)
                    gas_min_dicts = http.request.env.cr.dictfetchall()
                    _logger.info('***gas_min_dicts***')
                    _logger.info(gas_min_dicts)

                    sql = "select to_char(collection_date,'HH24:MI') as index_time, " \
                          "normal_temp_value as value " \
                          "from wliot_device_indicator_log a " \
                          "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.abnormal_temp_value=0 " \
                          "order by to_char(collection_date,'HH24:MI') asc " % (start_time, end_time)
                    http.request.env.cr.execute(sql)
                    temp_min_dicts = http.request.env.cr.dictfetchall()
                    _logger.info('***temp_min_dicts***')
                    _logger.info(temp_min_dicts)

                    data = {
                        'log_length': len(temp_min_dicts),
                        'gas_log': gas_min_dicts[offser_val:(offser_val + pageSize)],
                        'temp_log': temp_min_dicts[offser_val:(offser_val + pageSize)],
                    }
                else:
                    if days <= 1:
                        sql = "select to_char(collection_date,'HH24:MI') as index_time, " \
                              "max(normal_gas_value) as value " \
                              "from wliot_device_indicator_log a " \
                              "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.abnormal_gas_value=0 " \
                              "group by to_char(collection_date,'HH24:MI') " \
                              "order by to_char(collection_date,'HH24:MI') asc " % (start_time, end_time)
                        http.request.env.cr.execute(sql)
                        gas_hour_dicts = http.request.env.cr.dictfetchall()
                        _logger.info('***gas_hour_dicts***')
                        _logger.info(gas_hour_dicts)

                        sql = "select to_char(collection_date,'HH24:MI') as index_time, " \
                              "max(normal_temp_value) as value " \
                              "from wliot_device_indicator_log a " \
                              "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.abnormal_temp_value=0 " \
                              "group by to_char(collection_date,'HH24:MI')" \
                              "order by to_char(collection_date,'HH24:MI') asc " % (start_time, end_time)
                        http.request.env.cr.execute(sql)
                        temp_hour_dicts = http.request.env.cr.dictfetchall()
                        _logger.info('***temp_hour_dicts***')
                        _logger.info(temp_hour_dicts)

                        data = {
                            'gas_log': gas_hour_dicts[offser_val:(offser_val + pageSize)],
                            'temp_log': temp_hour_dicts[offser_val:(offser_val + pageSize)],
                            'log_length': len(gas_hour_dicts)
                        }
                    elif days > 1:
                        sql = "select to_char(collection_date,'MM-DD') as index_time, " \
                              "max(normal_gas_value) as value " \
                              "from wliot_device_indicator_log a " \
                              "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.abnormal_gas_value=0 " \
                              "group by to_char(collection_date,'MM-DD') " \
                              "order by to_char(collection_date,'MM-DD') asc " % (start_time, end_time)
                        http.request.env.cr.execute(sql)
                        gas_day_dicts = http.request.env.cr.dictfetchall()
                        _logger.info('***gas_day_dicts***')
                        _logger.info(gas_day_dicts)

                        sql = "select to_char(collection_date,'MM-DD') as index_time, " \
                              "max(normal_temp_value) as value " \
                              "from wliot_device_indicator_log a " \
                              "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.abnormal_temp_value=0 " \
                              "group by to_char(collection_date,'MM-DD') " \
                              "order by to_char(collection_date,'MM-DD') asc " % (start_time, end_time)
                        http.request.env.cr.execute(sql)
                        temp_day_dicts = http.request.env.cr.dictfetchall()
                        _logger.info('***temp_day_dicts***')
                        _logger.info(temp_day_dicts)

                        data = {
                            'gas_log': gas_day_dicts[offser_val:offser_val + pageSize],
                            'temp_log': temp_day_dicts[offser_val:offser_val + pageSize],
                            'log_length': len(gas_day_dicts)
                        }
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
            elif type == 'leak':
                if hours <= 1:
                    sql = "select to_char(collection_date,'HH24:MI') as index_time, " \
                          "abnormal_gas_value as value " \
                          "from wliot_device_indicator_log a " \
                          "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.normal_gas_value=0 " \
                          "order by to_char(collection_date,'HH24:MI') asc " % (start_time, end_time)
                    http.request.env.cr.execute(sql)
                    gas_min_dicts = http.request.env.cr.dictfetchall()
                    _logger.info('***gas_min_dicts2***')
                    _logger.info(gas_min_dicts)

                    data = {
                        'gas_log': gas_min_dicts[offser_val:offser_val + pageSize],
                        'log_length': len(gas_min_dicts)
                    }
                else:
                    if days <= 1:
                        sql = "select to_char(collection_date,'HH24:MI') as index_time, " \
                              "max(abnormal_gas_value),collection_date " \
                              "from wliot_device_indicator_log a " \
                              "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.normal_gas_value=0 " \
                              "group by to_char(collection_date,'HH24:MI') " \
                              "order by to_char(collection_date,'HH24:MI') asc " % (start_time, end_time)
                        http.request.env.cr.execute(sql)
                        gas_hour_dicts = http.request.env.cr.dictfetchall()
                        _logger.info('***gas_hour_dicts2***')
                        _logger.info(gas_hour_dicts)

                        data = {
                            'gas_log': gas_hour_dicts[offser_val:offser_val + pageSize],
                            'log_length': len(gas_hour_dicts)
                        }
                    elif days > 1:
                        sql = "select to_char(collection_date,'MM-DD') as index_time, " \
                              "max(abnormal_gas_value) " \
                              "from wliot_device_indicator_log a " \
                              "where (a.collection_date >= '%s') and (a.collection_date <= '%s') and a.normal_gas_value=0 " \
                              "group by to_char(collection_date,'MM-DD') " \
                              "order by to_char(collection_date,'MM-DD') asc " % (start_time, end_time)
                        http.request.env.cr.execute(sql)
                        gas_day_dicts = http.request.env.cr.dictfetchall()
                        _logger.info('***gas_day_dicts2***')
                        _logger.info(gas_day_dicts)

                        data = {
                            'gas_log': gas_day_dicts[offser_val:offser_val + pageSize],
                            'log_length': len(gas_day_dicts)
                        }
                return json.dumps({
                    'success': True,
                    'message': u'查询成功！',
                    'data': data
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'messgae': error,
                    'code': 500
                })

    @http.route('/wliot/device/updateDeviceBasic', auth='public', csrf=False)
    def updateDeviceBasic(self, **kw):
        ''' 修改设备基础信息 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': ''
                })

            location = kw.get('location')
            barcode = kw.get('barcode')
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            attrs = http.request.env['wliot.device.attribute'].sudo().search([
                ('device', '=', device.id)
            ])
            if attrs:
                attrs.unlink()
            attributes = kw.get('attributes')
            attributes = str(attributes)
            attributes = attributes.split(',')
            _logger.info(attributes)

            for attribute in attributes:
                http.request.env['wliot.device.attribute'].sudo().create({
                    'device': device.id,
                    'description': attribute
                })

            device.write({
                'location': location
            })
            return json.dumps({
                'success': True,
                'mwssage': u'修改成功！',
                'code': 200
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'message': error,
                    'code': 500
                })

    def get_beijing_datetime(self, uploadtime):
        return (datetime.datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S',
                                                         time.localtime(int((long(uploadtime)) * (
                                                                 10 ** (10 - len(str(uploadtime))))))),
                                           '%Y-%m-%d %H:%M:%S') + datetime.timedelta(hours=8)).strftime(
            '%Y-%m-%d %H:%M:%S')

    def timestamp2datetime(self, kw):
        return datetime.datetime.fromtimestamp((long(kw)) * (
                10 ** (10 - len(str(kw))))) + datetime.timedelta(hours=8)

    def get_partner_by_session_id(self, kw):
        '''检查session是否过期，并根据session_id返回该微信号可以查看的客户'''
        session_id = kw.get('SessionID')
        if not session_id:
            return {
                'success': False,
                'code': 400,
                'msg': u'请传入session_id！',
            }
        open_id = session_obj.pydis.get(session_id)
        if not open_id:
            return {
                'success': False,
                'code': 900,
                'msg': u'sessoin已过期，请重新获取！',
            }
        wechat_recs = http.request.env['weixin.user'].sudo().search([('open_id', '=', open_id)])
        partner = http.request.env['res.partner'].sudo().search([('id', '=', wechat_recs.partner_id.id)])
        return partner

    def check_phone_legal(self, phone):
        '''是否存在该电话的客户，若存在则返回该客户'''
        records = http.request.env['res.partner'].sudo().search([
            # ('partner_type', '=', 'customer'),
            ('phone', '=', phone)
        ])
        if not records:
            return {
                'success': False,
                'msg': u'不存在电话为%s的客户！' % phone,
            }
        else:
            return {
                'success': True,
                'value': records,
            }